import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Input,
  Form,
  Space,
  Button,
  Divider,
  Alert,
  Tag,
  Typography,
  Spin,
  message
} from 'antd';
import {
  EyeOutlined,
  SendOutlined,
  ReloadOutlined,
  CopyOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import { PromptTemplate, PromptVariable } from '@/types/prompt';
import { variableService } from '@/services/variable.service';
import { generationService } from '@/services/generation.service';
import { ModelType } from '@/types/models';
import './style.css';

const { TextArea } = Input;
const { Text, Title } = Typography;

interface PromptPreviewProps {
  template: PromptTemplate;
  variables?: Record<string, any>;
  testInput?: string;
  showLiveTest?: boolean;
  onVariableChange?: (variables: Record<string, any>) => void;
  onTest?: (result: string) => void;
  className?: string;
}

const PromptPreview: React.FC<PromptPreviewProps> = ({
  template,
  variables: initialVariables = {},
  testInput: initialTestInput = '',
  showLiveTest = true,
  onVariableChange,
  onTest,
  className = ''
}) => {
  const [form] = Form.useForm();
  const [variables, setVariables] = useState<Record<string, any>>(initialVariables);
  const [processedPrompt, setProcessedPrompt] = useState<string>('');
  const [testInput, setTestInput] = useState(initialTestInput);
  const [testOutput, setTestOutput] = useState<string>('');
  const [testing, setTesting] = useState(false);
  const [previewMode, setPreviewMode] = useState<'system' | 'full'>('system');
  
  // 处理变量变化
  useEffect(() => {
    const processed = variableService.replaceVariables(
      template.systemPrompt || '',
      variables
    );
    setProcessedPrompt(processed);
  }, [template, variables]);
  
  // 处理变量输入
  const handleVariableChange = (key: string, value: any) => {
    const newVariables = { ...variables, [key]: value };
    setVariables(newVariables);
    form.setFieldsValue({ [key]: value });
    
    if (onVariableChange) {
      onVariableChange(newVariables);
    }
  };
  
  // 自动填充示例值
  const handleAutoFill = () => {
    const exampleVariables: Record<string, any> = {};
    
    template.variables.forEach(variable => {
      if (variable.defaultValue !== undefined) {
        exampleVariables[variable.name] = variable.defaultValue;
      } else {
        // 根据类型生成示例值
        switch (variable.type) {
          case 'string':
            exampleVariables[variable.name] = `示例${variable.name}`;
            break;
          case 'number':
            exampleVariables[variable.name] = 10;
            break;
          case 'boolean':
            exampleVariables[variable.name] = true;
            break;
          case 'select':
            exampleVariables[variable.name] = variable.options?.[0] || '';
            break;
        }
      }
    });
    
    setVariables(exampleVariables);
    form.setFieldsValue(exampleVariables);
    message.success('已填充示例值');
  };
  
  // 测试提示词效果
  const handleTest = async () => {
    if (!testInput) {
      message.warning('请输入测试内容');
      return;
    }
    
    setTesting(true);
    try {
      // 构建测试请求
      const systemMessage = variableService.replaceVariables(
        template.systemPrompt || '',
        variables
      );
      
      const userMessage = template.userPromptPrefix 
        ? `${variableService.replaceVariables(template.userPromptPrefix, variables)}\n${testInput}`
        : testInput;
      
      const response = await generationService.generate({
        model: ModelType.GPT35,
        messages: [
          { role: 'system', content: systemMessage },
          { role: 'user', content: userMessage }
        ],
        parameters: {
          temperature: 0.7,
          topP: 0.85,
          maxTokens: 500,
          presencePenalty: 0,
          frequencyPenalty: 0
        },
        promptTemplate: template,
        promptVariables: variables
      });
      
      if (response.error) {
        throw new Error(response.error);
      }
      
      setTestOutput(response.content);
      if (onTest) {
        onTest(response.content);
      }
      message.success('测试完成');
    } catch (error) {
      console.error('Test failed:', error);
      message.error('测试失败，请稍后重试');
    } finally {
      setTesting(false);
    }
  };
  
  // 复制处理后的提示词
  const handleCopy = () => {
    navigator.clipboard.writeText(processedPrompt).then(() => {
      message.success('已复制到剪贴板');
    });
  };
  
  // 渲染变量输入表单
  const renderVariableForm = () => {
    if (template.variables.length === 0) {
      return <Alert message="此提示词没有变量" type="info" showIcon />;
    }
    
    return (
      <Form
        form={form}
        layout="vertical"
        initialValues={variables}
        onValuesChange={(_, allValues) => {
          setVariables(allValues);
          if (onVariableChange) {
            onVariableChange(allValues);
          }
        }}
      >
        <Row gutter={16}>
          {template.variables.map((variable: PromptVariable) => (
            <Col key={variable.name} xs={24} sm={12}>
              <Form.Item
                name={variable.name}
                label={
                  <Space>
                    <span>{variable.name}</span>
                    {variable.required && <Text type="danger">*</Text>}
                    {variable.description && (
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        ({variable.description})
                      </Text>
                    )}
                  </Space>
                }
                rules={[
                  {
                    required: variable.required,
                    message: `请输入${variable.name}`
                  },
                  variable.validation ? {
                    pattern: new RegExp(variable.validation),
                    message: '格式不正确'
                  } : {}
                ]}
              >
                {variable.type === 'select' ? (
                  <Select>
                    {variable.options?.map(option => (
                      <Select.Option key={option} value={option}>
                        {option}
                      </Select.Option>
                    ))}
                  </Select>
                ) : variable.type === 'boolean' ? (
                  <Select>
                    <Select.Option value={true}>是</Select.Option>
                    <Select.Option value={false}>否</Select.Option>
                  </Select>
                ) : variable.type === 'number' ? (
                  <InputNumber style={{ width: '100%' }} />
                ) : (
                  <Input placeholder={`请输入${variable.name}`} />
                )}
              </Form.Item>
            </Col>
          ))}
        </Row>
      </Form>
    );
  };
  
  return (
    <div className={`prompt-preview ${className}`}>
      <Row gutter={16}>
        {/* 变量输入区 */}
        <Col xs={24} lg={10}>
          <Card
            title="变量设置"
            extra={
              <Button
                size="small"
                icon={<ThunderboltOutlined />}
                onClick={handleAutoFill}
              >
                自动填充
              </Button>
            }
          >
            {renderVariableForm()}
          </Card>
          
          {showLiveTest && (
            <Card title="测试输入" style={{ marginTop: 16 }}>
              <TextArea
                value={testInput}
                onChange={e => setTestInput(e.target.value)}
                placeholder="输入测试内容，查看提示词效果..."
                rows={4}
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleTest}
                loading={testing}
                disabled={!testInput}
                style={{ marginTop: 12 }}
                block
              >
                测试效果
              </Button>
            </Card>
          )}
        </Col>
        
        {/* 预览区 */}
        <Col xs={24} lg={14}>
          <Card
            title="实时预览"
            extra={
              <Space>
                <Button.Group>
                  <Button
                    size="small"
                    type={previewMode === 'system' ? 'primary' : 'default'}
                    onClick={() => setPreviewMode('system')}
                  >
                    系统提示词
                  </Button>
                  <Button
                    size="small"
                    type={previewMode === 'full' ? 'primary' : 'default'}
                    onClick={() => setPreviewMode('full')}
                  >
                    完整预览
                  </Button>
                </Button.Group>
                <Button
                  size="small"
                  icon={<CopyOutlined />}
                  onClick={handleCopy}
                >
                  复制
                </Button>
              </Space>
            }
          >
            {/* 变量高亮显示 */}
            <div className="variable-highlights">
              <Text type="secondary">当前变量值：</Text>
              <Space wrap style={{ marginTop: 8 }}>
                {Object.entries(variables).map(([key, value]) => (
                  <Tag key={key} color="blue">
                    {key}: {String(value)}
                  </Tag>
                ))}
              </Space>
            </div>
            
            <Divider />
            
            {/* 预览内容 */}
            <div className="preview-content">
              {previewMode === 'system' ? (
                <>
                  <Title level={5}>系统提示词</Title>
                  <pre className="prompt-text">{processedPrompt}</pre>
                  
                  {template.userPromptPrefix && (
                    <>
                      <Divider />
                      <Title level={5}>用户提示词前缀</Title>
                      <pre className="prompt-text">
                        {variableService.replaceVariables(
                          template.userPromptPrefix,
                          variables
                        )}
                      </pre>
                    </>
                  )}
                </>
              ) : (
                <>
                  <Title level={5}>完整对话预览</Title>
                  <div className="conversation-preview">
                    <div className="message system-message">
                      <Tag color="purple">System</Tag>
                      <pre>{processedPrompt}</pre>
                    </div>
                    {template.userPromptPrefix && testInput && (
                      <div className="message user-message">
                        <Tag color="blue">User</Tag>
                        <pre>
                          {variableService.replaceVariables(
                            template.userPromptPrefix,
                            variables
                          )}
                          {'\n'}
                          {testInput}
                        </pre>
                      </div>
                    )}
                  </div>
                </>
              )}
            </div>
            
            {/* 测试输出 */}
            {testOutput && (
              <>
                <Divider />
                <div className="test-output">
                  <Title level={5}>
                    <Space>
                      测试输出
                      <Button
                        size="small"
                        icon={<ReloadOutlined />}
                        onClick={handleTest}
                        loading={testing}
                      >
                        重新测试
                      </Button>
                    </Space>
                  </Title>
                  <Spin spinning={testing}>
                    <pre className="output-text">{testOutput}</pre>
                  </Spin>
                </div>
              </>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

// 需要的额外导入
import { Select, InputNumber } from 'antd';

export default PromptPreview;